import axios, { AxiosError } from 'axios'
import { ElMessage } from 'element-plus'
import type {
  ApiResponse,
  Message,
  ChatRequest,
  ChatResponse,
  PromptRequest,
  PromptResponse,
  ApiError
} from './types'

// API 错误处理类
export class ApiException extends Error {
  constructor(public code: number, message: string, public details?: any) {
    super(message)
    this.name = 'ApiException'
  }
}

// API 基础配置
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api/v1',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const apiKey = localStorage.getItem('deepseek_api_key')
    if (apiKey) {
      config.headers['Authorization'] = `Bearer ${apiKey}`
    }
    return config
  },
  (error) => {
    console.error('请求配置错误:', error)
    return Promise.reject(new ApiException(500, '请求配置错误'))
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    const { data } = response
    if (data.code && data.code !== 200) {
      throw new ApiException(data.code, data.message, data.details)
    }
    return data
  },
  (error: AxiosError<ApiError>) => {
    let apiError: ApiException

    if (error.response) {
      const { status, data } = error.response
      switch (status) {
        case 401:
          ElMessage.error('未授权，请检查 API 密钥')
          localStorage.removeItem('deepseek_api_key')
          window.location.href = '/settings'
          apiError = new ApiException(status, '未授权，请检查 API 密钥')
          break
        case 403:
          ElMessage.error('权限不足')
          apiError = new ApiException(status, '权限不足')
          break
        case 429:
          ElMessage.error('请求过于频繁，请稍后再试')
          apiError = new ApiException(status, '请求频率限制')
          break
        default:
          const message = data?.message || '请求失败'
          ElMessage.error(message)
          apiError = new ApiException(status, message, data?.details)
      }
    } else if (error.request) {
      ElMessage.error('网络错误，请检查网络连接')
      apiError = new ApiException(500, '网络错误')
    } else {
      ElMessage.error('请求配置错误')
      apiError = new ApiException(500, '请求配置错误')
    }

    console.error('API错误:', apiError)
    return Promise.reject(apiError)
  }
)

// API 接口
export const deepseekApi = {
  // 聊天接口
  chat: async (params: ChatRequest): Promise<ApiResponse<ChatResponse>> => {
    return await api.post('/deepseek/chat', params)
  },

  // 生成提示词接口
  generatePrompt: async (params: PromptRequest): Promise<ApiResponse<PromptResponse>> => {
    return await api.post('/deepseek/generate_prompt', params)
  },

  // 验证API密钥
  validateApiKey: async (apiKey: string): Promise<ApiResponse<boolean>> => {
    return await api.post('/deepseek/validate_key', { api_key: apiKey })
  }
} 